<?php
/**
 * 买家的订单管理控制器
 * Created by PhpStorm.
 * User: Jmashimaro
 * Date: 2015/2/7
 * Time: 18:53
 */
class BuyerOrderApp extends FrontendApp {

    /**
     * 订单列表
     * @author jiayanxiu
     * @date 2015/02/05
     */
    public function index() {

        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        $config = require ROOT_PATH.'/data/config.qiniu.php';

        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR ,'非法的请求！');
        }
        $user_id = $this->checkLogin();
        if(!$user_id){
            $this->ajax_return(FLAG_ERROR ,'请您登陆！');
        }
        $offset = $this->get_gp('offset', 'G');
        $size = $this->get_gp('size', 'G');
        $type = $this->get_gp('type', 'G');
        $offset = $offset ? intval($offset) : 0;
        $size = $size ? intval($size) : 10;
        $model_order = m('order');

        if($type === 'other'){
            $conditions = ' AND `status` IN (11,20,30) ';
        }else if($type === 'finished') {
            $conditions = ' AND `status` = 40';
        } else {
            $conditions = ' ';
        }
        /* 查找订单 */
        $orders = $model_order->findAll(array(
            'conditions'    => "buyer_id= {$user_id}{$conditions}",
            'fields'        => 'this.*',
            'count'         => true,
            'limit'         => "{$offset}, {$size}",
            'order'         => 'add_time DESC',
            'include'       =>  array(
                'has_ordergoods',       //取出商品
            ),
        ));
        $data = array();
        if ($orders) {
            foreach ((array)$orders as $key=>$value) {
                $sql = "SELECT store_logo FROM ".DB_PREFIX."store WHERE store_id={$value['seller_id']}";
                $value['store_logo'] = $config['qiniu_url'].$model_order->getOne($sql);
                $row = array();
                foreach ((array)$value['order_goods'] as $k=>$v) {
                    $v['goods_image'] = $v['goods_image'] ? $config['qiniu_url'].$v['goods_image'] : Conf::get('default_goods_image');
                    $row[] = $v;
                }
                unset($value['order_goods']);
                $value['order_goods'] = $row;
                $data[] = $value;
            }
        }
        $this->ajax_return(FLAG_OK,'',$data);
    }

    //订单详情
    public function detail() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        $config = require ROOT_PATH.'/data/config.qiniu.php';
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR ,'非法的请求！');
        }
        $order_id = $this->get_gp('order_id', 'G');
        $user_id = $this->checkLogin();
        if(!$user_id) {
            $this->ajax_return(FLAG_ERROR, '请您登陆！');
        }
        $sql = "select * from ".DB_PREFIX."order a left join ".DB_PREFIX."store b on a.seller_id = b.store_id
                left join ".DB_PREFIX."address c on a.buyer_id = c.user_id left join ".DB_PREFIX."shipping d
                on b.store_id = d.store_id where a.order_id = {$order_id} AND a.buyer_id = {$user_id}";
        $store_sql = "SELECT * FROM ".DB_PREFIX."store a left join ".DB_PREFIX."order b on a.store_id = b.seller_id where b.order_id = {$order_id} ";
        $model_order = m('order');
        $order = $model_order->getRow($sql);
        $store = $model_order->getRow($store_sql);
        $order['region_name'] = str_replace("\t",'',$order['region_name']);        //买家地址
        $order['seller_region'] = $store['region_name'];                           //卖家地址
        $order['seller_address'] = $store['address'];                              //卖家详细地址
        $order['store_logo'] = $config['qiniu_url'].$order['store_logo'];
        $sql = "SELECT * FROM ".DB_PREFIX."order_goods WHERE order_id = {$order['order_id']}";
        $good_list = $model_order->getAll($sql);
        foreach($good_list as $key=>$val){
            $good_list[$key]['goods_image']=$config['qiniu_url'].$val['goods_image'];
        }
        $order["goods_list"] = $good_list;
        if (!$order) {
            $this->ajax_return(FLAG_ERROR, '订单信息不存在，请您重试！');
        }
        $this->ajax_return(FLAG_OK,'', $order);
    }

    /**
     * 确认收货
     * @author lizhuang
     * @date 2015/04/16
     */
    public function confirm(){
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR ,'非法的请求！');
        }
        $order_id = $this->get_gp('order_id', 'G');
        $user_id = $this->checkLogin();
        if(!$user_id) {
            $this->ajax_return(FLAG_ERROR, '请您登陆！');
        }
        $model_order = m('order');
        $sql = "SELECT status FROM ".DB_PREFIX."order WHERE order_id = {$order_id}";
        $statue = $model_order->getOne($sql);
        if(!$statue){
            $this->ajax_return(FLAG_ERROR, '该订单不存在');
        }
        if($statue == ORDER_FINISHED){
            $this->ajax_return(FLAG_ERROR, '该商品已经确认收货');
        }
        if($statue != ORDER_SHIPPED){
            $this->ajax_return(FLAG_ERROR, '该商品暂未发货');
        }
        //更新订单状态为ORDER_FINISHED 表示确认收货
        $data = array(
            'status'=> ORDER_FINISHED
        );
        $update = $model_order->edit("order_id = {$order_id} AND buyer_id = {$user_id}",$data);
        if($update){
            $this->ajax_return(FLAG_OK,'操作成功');
        }else{
            $this->ajax_return(FLAG_ERROR, '操作失败');
        }
    }
    /**
     * 取消订单
     * @author lizhuang
     * @date 2015/04/16
     */
    public function cancel(){
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR ,'非法的请求！');
        }
        $order_id = $this->get_gp('order_id', 'G');
        $user_id = $this->checkLogin();
        if(!$user_id) {
            $this->ajax_return(FLAG_ERROR, '请您登陆！');
        }
        $model_order = m('order');
        $sql = "SELECT status FROM ".DB_PREFIX."order WHERE order_id = {$order_id}";
        $statue = $model_order->getOne($sql);
        if(!$statue){
            $this->ajax_return(FLAG_ERROR, '该订单不存在或已取消');
        }
        if($statue == ORDER_SHIPPED){
            $this->ajax_return(FLAG_ERROR, '不可以取消订单');
        }
        //更新订单状态为ORDER_CANCELED 表示取消该订单
        $data = array(
            'status'=> ORDER_CANCELED
        );
        $update = $model_order->edit("order_id = {$order_id} AND buyer_id = {$user_id}",$data);
        if($update){
            $this->ajax_return(FLAG_OK,'取消成功');
        }else{
            $this->ajax_return(FLAG_ERROR, '取消失败');
        }
    }

    /**
     * 查询微信支付订单
     * @author jiayanxiu
     * @date 2015/05/15
     */
    public function orderQuery() {
        include_once(ROOT_PATH."/includes/payments/WxPayPubHelper/WxPay.pub.config.php");
        include_once(ROOT_PATH."/includes/payments/WxPayPubHelper/WxPayPubHelper.php");
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR ,'非法的请求！');
        }
        $user_id = $this->checkLogin();
        if(!$user_id) {
            $this->ajax_return(FLAG_ERROR, '请您登陆！');
        }
        $orderId = $this->get_gp('orderID', 'P');
        $order_model = m('order');
        $sql = "SELECT o.order_sn,o.order_amount,og.goods_name FROM `".DB_PREFIX."order` o LEFT JOIN ".DB_PREFIX."order_goods og
                ON o.order_id=og.order_id WHERE o.order_id={$orderId} LIMIT 1";
        $orderInfo = $order_model->getRow($sql);
        if (!$orderInfo) {
            $this->ajax_return(FLAG_ERROR, '订单信息不存在！');
        }
        //微信统一下单
        $input = new UnifiedOrder_pub();
        $input->setParameter('body', $orderInfo['goods_name']);
        $input->setParameter('out_trade_no', $orderInfo['order_sn']);
        $input->setParameter('total_fee', floatval($orderInfo['order_amount'] * 100));
        $input->setParameter('time_start', date("YmdHis"));
        $input->setParameter('time_expire', date("YmdHis", time() + 600));
        $input->setParameter('notify_url', WxPayConf_pub::NOTIFY_URL);
        $input->setParameter('trade_type', 'APP');
        $row = $input->getPrepayId();

        if ($row['return_code'] == 'SUCCESS' && $row['result_code'] == 'FAIL') {
            $this->ajax_return(FLAG_ERROR, '该订单已经支付！');
        } elseif ($row['return_code'] == 'SUCCESS' && $row['result_code'] == 'SUCCESS') {
            $res['timestamp']   = time();
            $res['appid']       = $row['appid'];
            $res['partnerid']   = $row['mch_id'];
            $res['noncestr']    = $row['nonce_str'];
            $res['prepayid']    = $row['prepay_id'];
            $res['package']     = 'Sign=WXPay';
            $res['sign'] = $input->getSign($res);
            $this->ajax_return(FLAG_OK, '', $res);
        } else {
            $this->ajax_return(FLAG_ERROR, '微信支付失败！');
        }

    }

}